<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { getStudentCountDataApi, type StudentCountDTO } from '@/api/stu'

// 学历统计数据
const degreeData = ref<{ degree: number; count: number }[]>([])
// 班级人数统计数据 - 修正为数组类型
const clazzData = ref<StudentCountDTO[]>([])

const degreeChartRef = ref()
const clazzChartRef = ref()
let degreeChart: echarts.ECharts | null = null
let clazzChart: echarts.ECharts | null = null

// 获取学历统计
const fetchDegreeData = async () => {
  try {
    const res = await request.get('/students/report/studentDegreeData')
    if (res && res.code) {
      degreeData.value = res.data || []
    } else {
      degreeData.value = []
      ElMessage.error(res?.msg || '获取学历统计失败')
    }
  } catch (e) {
    degreeData.value = []
    ElMessage.error('获取学历统计失败')
  }
}

// 获取班级人数统计
const fetchClazzData = async () => {
  try {
    const res = await getStudentCountDataApi()
    if (res && res.code) {
      clazzData.value = res.data || []
    } else {
      clazzData.value = []
      ElMessage.error(res?.msg || '获取班级人数统计失败')
    }
  } catch (e) {
    clazzData.value = []
    ElMessage.error('获取班级人数统计失败')
    console.error('API调用失败:', e)
  }
}

// 渲染学历统计图
const renderDegreeChart = () => {
  if (!degreeChartRef.value) return
  if (!degreeChart) {
    degreeChart = echarts.init(degreeChartRef.value)
  }
  const option = {
    title: { text: '学历分布', left: 'center' },
    tooltip: { trigger: 'item' },
    legend: { orient: 'vertical', left: 'left' },
    series: [
      {
        name: '学历',
        type: 'pie',
        radius: '60%',
        data: degreeData.value.map((item) => ({
          value: item.count,
          name: (() => {
            switch (item.degree) {
              case 1:
                return '大专'
              case 2:
                return '本科'
              case 3:
                return '硕士'
              case 4:
                return '博士'
              default:
                return '其他'
            }
          })(),
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }
  degreeChart.setOption(option)
}

// 渲染班级人数统计图
const renderClazzChart = () => {
  if (!clazzChartRef.value || !clazzData.value?.length) return

  if (!clazzChart) {
    clazzChart = echarts.init(clazzChartRef.value)
  }

  const option = {
    title: { text: '班级人数分布', left: 'center' },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c}人',
    },
    xAxis: {
      type: 'category',
      data: clazzData.value.map((item) => item.clazzName),
      axisLabel: {
        rotate: 45,
        interval: 0,
      },
    },
    yAxis: {
      type: 'value',
      name: '人数',
    },
    series: [
      {
        name: '人数',
        data: clazzData.value.map((item) => item.data),
        type: 'bar',
        barWidth: '50%',
        itemStyle: {
          color: '#3b82f6',
          borderRadius: [4, 4, 0, 0],
        },
        label: {
          show: true,
          position: 'top',
        },
      },
    ],
  }
  clazzChart.setOption(option)
}

onMounted(async () => {
  await fetchDegreeData()
  await fetchClazzData()
  renderDegreeChart()
  renderClazzChart()
})
</script>

<template>
  <div class="stu-count-container">
    <h1>学生数据统计</h1>
    <div class="charts-row">
      <div class="chart-card">
        <div ref="degreeChartRef" class="chart-box"></div>
        <div v-if="!degreeData?.length" class="empty-tip">暂无学历统计数据</div>
      </div>
      <div class="chart-card">
        <div ref="clazzChartRef" class="chart-box"></div>
        <div v-if="!clazzData?.length" class="empty-tip">暂无班级人数数据</div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.stu-count-container {
  max-width: 1100px;
  margin: 0 auto;
  padding: 32px 0;
}
.charts-row {
  display: flex;
  gap: 32px;
  justify-content: center;
  align-items: flex-start;
}
.chart-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 16px 0 rgba(60, 72, 100, 0.06);
  border: 1px solid #f0f1f3;
  padding: 24px;
  width: 480px;
  min-height: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}
.chart-box {
  width: 400px;
  height: 320px;
}
.empty-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #aaa;
  font-size: 16px;
}
@media (max-width: 1100px) {
  .charts-row {
    flex-direction: column;
    gap: 24px;
    align-items: center;
  }
  .chart-card {
    width: 98vw;
    min-width: 0;
    padding: 12px;
  }
  .chart-box {
    width: 90vw;
    min-width: 0;
  }
}
</style>
